<?php

namespace common\extend\plugins;

use yii\db\Exception;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;

/**
 * 提供基于ActiveRecord的分表功能
 * 注意：因为通过ActiveRecord查询的表名是固定static::tableName()来获取静态的，
 *          每次声明的表明都会固定，多次不同分表都要在每次查询前重新设置表名
 *      或者使用 ->from(SubTableModel::tableNameByKey($id)) 来手动指定
 * Class SubTableModel
 * @package common\extend\plugins
 */
class SubTableModel extends ActiveRecord
{
    use SubTableTrait;

    /**
     * SubTableModel constructor.
     * @param null $id
     * @param array $config
     * @throws Exception
     */
    public function __construct($id = null, $config = [])
    {
        if ($id !== null) static::setTableNameByKey($id);
        parent::__construct($config);
    }

    /**
     * 分表依据的字段
     * @return string
     */
    public static function limitByField(): string
    {
        return 'id';
    }

    /**
     * 模仿Model模式
     * @param $id
     * @return ActiveQuery
     * @throws Exception
     */
    public static function find($id = null): ActiveQuery
    {
        if ($id !== null) static::setTableNameByKey($id);
        return parent::find();
    }


    /**
     * @param mixed $condition
     * @param null $id
     * @return static|null
     * @throws Exception
     */
    public static function findOne($condition,$id = null): ?static
    {
        $limitByField = static::limitByField();
        $subKey = null;
        if ($limitByField){
            if ($id !== null){
                $subKey = $id;
            } else {
                if (is_array($condition)){
                   if (isset($condition[$limitByField])) $subKey = $condition[$limitByField];
                } else {
                    if ($limitByField == 'id'){
                        $subKey = $condition;
                    }
                }
            }
        }
        if ($subKey !== null) static::setTableNameByKey($subKey);
        return parent::findOne($condition);
    }
}